package ct.zxd.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ct.zxd.db.Dao;

public class HandleDish extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;character=utf-8");  
        response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String show="",name="",category="",categoryid="",priceStr="",stockStr="",front="";
		String imageURL = "", introduce = "";
		float price=1;
		int stock=1000;
		String flag = request.getParameter("flag");
		String shop = request.getParameter("shop");
		
		System.out.println("tu pian");
	
		// 上传了新的图片，表单的类型是否为multipart/form-data
		if (ServletFileUpload.isMultipartContent(request)) {
			
			
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置内存缓冲区的大小,设置为20KB，如果文件大于该设置值,将使用临时文件缓存上传文件 
			factory.setSizeThreshold(1024 * 20);
			
			String dir = request.getSession().getServletContext().getRealPath("/");
			dir =dir.substring(0, dir.length()-9); // "OrderSys\"长度为9
			dir+="ROOT"+File.separator+"upload";
			
			File file = new File(dir);
			if (!file.exists())file.mkdir();
			int fileCount = file.listFiles().length;
			
			String tempFilePath = dir + File.separator+"temp";
			file = new File(tempFilePath);
			if (!file.exists())file.mkdir();
			// 指定临时文件目录
			factory.setRepository(new File(tempFilePath));
			
			// 构建文件上传对象
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(1024 * 1024 * 1024);
			
			try {
				List<FileItem> list = upload.parseRequest(request);
				Iterator<FileItem> it = list.iterator();
				// 处理每一个FileItem
				while (it.hasNext()) {
					// 每一个item就代表一个表单输出项
					FileItem item = it.next();
					String formName = item.getFieldName();
					String formValue = item.getString();
					
					if (item.isFormField()) {// 判断input是否为普通表单输入项			
						
						if(formName.equals("showid"))show=formValue;
						if(formName.equals("title")){
							name=formValue;
							name = new String(name.getBytes("iso-8859-1"),"utf-8");
						}
						if(formName.equals("category")){
							category=formValue;
							String [] strArray = category.split("-");
							category = strArray[0];
							categoryid = strArray[1];
							category = new String(category.getBytes("iso-8859-1"),"utf-8");
						}
						if(formName.equals("price"))priceStr=formValue;
						if(formName.equals("stock"))stockStr=formValue;
						if(formName.equals("front"))front=formValue;
						if(formName.equals("img"))imageURL=formValue;
						if(formName.equals("imgDetail"))introduce=formValue;
						
					} else {
						
						if (formValue.isEmpty()) {  //没有上传新图片，不做处理
							continue;
						}
					    String newName = ++fileCount+".jpg" ;
						item.write(new File(dir+File.separator+newName));
						
						if (formName.equals("fileDetail")) {
							introduce="https://mall.weikedashi.net/upload/"+newName;
							introduce = new String(introduce.getBytes("iso-8859-1"),"utf-8");
						}
						if (formName.equals("file")) {
							imageURL="https://mall.weikedashi.net/upload/"+newName;
							imageURL = new String(imageURL.getBytes("iso-8859-1"),"utf-8");
						}
						out.print(formName+"上传成功<br>");
					}
				}
			} catch (FileSizeLimitExceededException e) {
				out.print("上传文件大小超过了6MB,重新输入");
				return;
				//request.setAttribute("errFile", "上传文件大小超过了2MB");
				//request.getRequestDispatcher("addadv.jsp?shop="+shop+"&flag="+flag+"&show="+show+"&cateName="+name).forward(request, response);
			} catch (Exception e) {
				out.print("系统出现错误，上传失败,请与管理员联系");
				this.getServletContext().log(e.toString());
			}
		
			
		}else{//如果不是上传了新的图片，则普通方式读取表单，而且不需要使用getBytes("iso-8859-1"),"utf-8")转码
			
			imageURL = request.getParameter("img");
			show = request.getParameter("showid");
			name = request.getParameter("title");
			
			//种类字段包含了种类名称和种类id,用 - 连接
			category = request.getParameter("category");
			String [] strArray = category.split("-");
			category = strArray[0];
			categoryid = strArray[1];
			
			priceStr = request.getParameter("price");
			stockStr = request.getParameter("stock");
			
			front = request.getParameter("front");
			introduce = request.getParameter("imgDetail");
		}
		
		try {
			price = Float.parseFloat(priceStr);
			stock = Integer.parseInt(stockStr);
		} catch (NumberFormatException e1) {	
			out.print("输入的价格或者库存不是数字，请重新输入");
			return;
		}
		
		try {
			Dao dao = new Dao();
			int count = 0;
			String html = "<script language=\"javascript\">parent.location.href='adv.jsp?shopid="+shop+"';</script>";
			
			if(flag.equals("del")){
				count = dao.deleteDish(show, shop);
			}else{
				if(dao.isExisted("dish", shop, name,show)){
					request.setAttribute("errName", name+"已存在，请重新输入");
					request.getRequestDispatcher("addadv.jsp?shop="+shop+"&flag="+flag+"&show="+show+"&cateName="+name).forward(request, response);   
				}else{
					if(flag.equals("update")){
						count = dao.updateDish(name, show, shop, price, stock, category, imageURL, categoryid, front, introduce);
					}else{
						 count = dao.insertDish(name, show, shop, price, stock, category, imageURL, categoryid, front, introduce);
					}
				}
			}
			
			if(count>0){
				out.write(html);
			}else{
				out.write("数据库出错，操作失败");
			}
			
		} catch (SQLException e) {
			System.out.println(e);
			out.write("服务器连接错误");
		}	
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
